<?php

namespace core;

class Route
{
    private $group; //分组
    private $routes = []; //分组下的路由, 包括分组

    private $nsParent; //父命名空间
    private $ns = ''; //分组命名空间

    private $middlewares; //分组中间件

    public function __construct(string $group, string $nsParent = '', array $middlewares = [])
    {
        $this->group       = $group;
        $this->nsParent    = $nsParent;
        $this->middlewares = $middlewares;
    }

    public function getGroup(): string
    {
        return $this->group;
    }

    public function setNamespace(string $ns): void
    {
        $this->ns = $ns;
    }

    public function getNamespace(): string
    {
        if (!$this->nsParent && !$this->ns) {
            return APP_CONTROLLER_NAMESPACE;
        }

        if ($this->ns) {
            return $this->ns;
        }
        if ($this->nsParent) {
            return $this->nsParent;
        }

        return '';
    }

    public function getRoutes(): array
    {
        return $this->routes;
    }

    public function addRoute(string $method, string $uri, $cb, $middleware): void
    {
        $method = strtoupper($method);
        slash_add($uri);

        $middlewares = [];
        if ($middleware && is_array($middleware)) {
            $middlewares = $middleware;
        } else if ($middleware) {
            $middlewares[] = $middleware;
        }

        $item = new RouteItem($method, $uri, $cb, $middlewares);

        $this->routes[] = $item;
    }

    public function addChild(Route $child): void
    {
        $this->routes[] = $child;
    }

    public function getMiddlewares(): array {
        return $this->middlewares;
    }

    public function addMiddleware($middleware): void {
        if (is_array($middleware)) {
            $this->middlewares = array_merge($this->middlewares, $middleware);
        } else {
            $this->middlewares[] = $middleware;
        }
    }
}
